package com.xlh.openai.listener;

import cn.hutool.core.date.DateUtil;
import com.xlh.openai.entity.OrderEntity;
import com.xlh.openai.entity.ProductEntity;
import com.xlh.openai.service.OrderService;
import com.xlh.openai.service.ProductService;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;


@Data
@Accessors(chain = true)
public class OrderDelay implements Delayed, Runnable{

    @ApiModelProperty("预定库存ID")
    private Integer orderId;

    @ApiModelProperty("执行时间")
    private Long second;

    @ApiModelProperty("订单Order")
    private OrderService orderService;

    @ApiModelProperty("产品Service")
    private ProductService productService;

    @Override
    public void run() {
        // 还原过期的订单库存
        Integer expire = 1;
        Integer notExpire = 0;
        OrderEntity orderEntity = orderService.getById(orderId);
        // 如果当前订单未支付
        if( orderEntity.getPayStatus() == 0
                && notExpire.equals(orderEntity.getIsExpire())){
            // 将订单置为过期状态
            orderEntity.setIsExpire(expire);
            // 并且将订单的东西还给库存
            ProductEntity orderProduct = productService.getById(orderEntity.getProductId());
            productService.increase( orderEntity.getId() ,orderProduct.getStock());
            orderService.updateById(orderEntity);
        }
    }

    @Override
    public long getDelay(TimeUnit unit) {
        Long currentSecond = DateUtil.currentSeconds();
        return TimeUnit.SECONDS.toSeconds((second - currentSecond));
    }

    @Override
    public int compareTo(Delayed delayed) {
        OrderDelay orderDelay = (OrderDelay)delayed;
        return this.second.compareTo(orderDelay.getSecond());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        OrderDelay that = (OrderDelay) o;
        return Objects.equals(orderId, that.orderId) &&
                Objects.equals(second, that.second) ;
    }

    @Override
    public int hashCode() {
        return Objects.hash(orderId, second);
    }
}
